<?php

namespace Admin\Controller;

use Lib\DataTable;

class DataController extends AuthController
{
    public function userList()
    {
        if (I('param.draw')) {
            $DataTable = new DataTable(D('UserView'));

            $DataTable->filter = ['game_user'];
//            $DataTable->map['status'] = array('egt', 0);
            $DataTable->lists();


            $DataTable->returnJson();
        }
        $this->display('user-list');
    }

    public function user()
    {
        $User = D('UserView');
        $map['game_user'] = array('like', '%' . I('param.query') . '%');
        $data = $User->where($map)->field('id,game_user as label,game')->limit(I('param.limit'))->select();

//        echo $User->getLastSql();
        exit(json_encode($data));
    }

    public
    function userEdit($id = '')
    {
        if (IS_POST) {
            $User = D('User'); // 实例化User对象
            if (!$User->create()) {
                // 如果创建失败 表示验证没有通过 输出错误提示信息
                show(0, $User->getError());
            } else {
                if ($User->where("gid='%s' and game_user='%s'", $User->gid, $User->game_user)->find()) {
                    show(0, '该用户已经存在，请查证！');
                }
                if ($id) {
                    //        编辑保存
                    $User->save();
                } else {
                    //        增加保存
                    $User->add();
                }
                show(1, '保存成功');
            }
        }
        $User = M('User'); // 实例化User对象
        $UserData = $User->find($id);

        $GameData = D('Game')->select();

        $this->assign('UserData', $UserData);
        $this->assign('GameData', $GameData);
        $this->display('user-edit');
    }

    public
    function userStatus($id, $status)
    {
        switch ($status) {
            case 'del':
                $data['status'] = -1;
                $action = '删除';
                break;
            case 'start':
                $action = '启用';
                $data['status'] = 1;
                break;
            case 'stop':
                $action = '停用';
                $data['status'] = 0;
                break;
            default:
                $action = '';
                show(0, '无效操作');
                break;
        }
        if (is_numeric($id)) {
            $data['id'] = $id;
            if (M('User')->save($data)) {
                show(1, $action . '成功');
            } else {
                show(0, $action . '失败');
            }
        }
        if (is_array($id)) {
            $succeed = 0;
            foreach ($id as $i => $item) {
                $data['id'] = $item;
                if (M('User')->save($data) != false) {
                    $succeed++;
                }
            }
            show(1, '共选择 ' . sizeof($id) . ' 条记录，成功' . $action . ' ' . $succeed . ' 条');
        }
    }
    public
    function dataRemove($id)
    {
        if (is_numeric($id)) {
            $id=array('id'=>$id);
        }

        if (is_array($id)) {
            $succeed = 0;
            foreach ($id as $i => $item) {
                if (M('Data')->delete($item)) {
                    $succeed++;
                }
            }
            show(1, '共选择 ' . sizeof($id) . ' 条记录，成功删除' . $succeed . '条');
        }
    }

    public
    function gameEdit($id = '')
    {
        if (IS_POST) {
            $Group = D('Game'); // 实例化User对象
            if (!$Group->create()) {
                // 如果创建失败 表示验证没有通过 输出错误提示信息
                show(0, $Group->getError());
            } else {
                if ($id) {
                    //        编辑保存
                    $Group->save();
                } else {
                    //        增加保存
                    $Group->add();
                }
                show(1, '保存成功');
            }
        }
        $Game = M('Game'); // 实例化User对象
        $GameData = $Game->find($id);


        $this->assign('GameData', $GameData);
        $this->display('game-edit');
    }

    public
    function gameStatus($id, $status)
    {
        switch ($status) {
            case 'del':
                $data['status'] = -1;
                $action = '删除';
                break;
            case 'start':
                $action = '启用';
                $data['status'] = 1;
                break;
            case 'stop':
                $action = '停用';
                $data['status'] = 0;
                break;
            default:
                $action = '';
                show(0, '无效操作');
                break;
        }
        if (is_numeric($id)) {
            $data['id'] = $id;
            if (M('Game')->save($data)) {
                show(1, $action . '成功');
            } else {
                show(0, $action . '失败');
            }
        }
        if (is_array($id)) {
            $succeed = 0;
            foreach ($id as $i => $item) {
                $data['id'] = $item;
                if (M('Game')->save($data) != false) {
                    $succeed++;
                }
            }
            show(1, '共选择 ' . sizeof($id) . ' 条记录，成功' . $action . ' ' . $succeed . ' 条');
        }
    }


    public function gameList()
    {
        if (I('param.draw')) {
            $DataTable = new DataTable(D('Game'));

            $DataTable->filter = ['name'];

//            $DataTable->map['status'] = array('egt', 0);
            $DataTable->lists();


            $DataTable->returnJson();
        }
        $this->display('game-list');
    }

    public function dataList()
    {
        if (I('param.draw')) {
            $DataTable = new DataTable(D('DataView'));

            $DataTable->filter = ['game_user', 'Game.name', 'mask','date'];

//            $DataTable->map['status'] = array('egt', 0);
            $DataTable->lists();


            $DataTable->returnJson();
        }

        $this->display('data-list');
    }

    function dataEdit($id = '')
    {
        if (IS_POST) {
            $Group = D('Data'); // 实例化User对象
            if (!$Group->create()) {
                // 如果创建失败 表示验证没有通过 输出错误提示信息
                show(0, $Group->getError());
            } else {
                if ($id) {
                    //        编辑保存
                    $Group->save();
                } else {
                    //        增加保存
                    $Group->add();
                }
                show(1, '保存成功');
            }
        }
        $Data = D('DataView')->find($id);
        $UserData = D('UserView')->select();

        $GameData = D('Game')->select();

        $this->assign('UserData', $UserData);
        $this->assign('GameData', $GameData);


        $this->assign('Data', $Data);
        $this->display('data-edit');
    }

    function dataImport()
    {
        if (IS_POST) {
            $date = I('post.date');
            $gid = I('post.gid');
            if (!$date) {
                show(0, '请选择日期！');

            }
            $upload = new \Think\Upload();// 实例化上传类
            $upload->maxSize = 3145728;// 设置附件上传大小
            $upload->exts = array('xls', 'xlsx');// 设置附件上传类型
            $upload->rootPath = './Uploads/'; // 设置附件上传根目录
            $upload->savePath = ''; // 设置附件上传（子）目录
            // 上传文件
            $info = $upload->upload();
            if (!$info) {// 上传错误提示错误信息
                show(0, $upload->getError());
            } else {// 上传成功
                $uploadfile = $upload->rootPath . $info['file']['savepath'] . $info['file']['savename'];
                Vendor('PHPExcel.PHPExcel');
                $reader = new \PHPExcel_Reader_Excel2007(); // 读取 excel 文档
                $PHPExcel = $reader->load($uploadfile); // 文档名称
                $sheet = $PHPExcel->getActiveSheet();
                $highestRow = $sheet->getHighestRow(); // 取得总行数
                $highestColumn = $sheet->getHighestColumn(); // 取得总行数
                $arr = array(1 => 'A', 2 => 'B', 3 => 'C', 4 => 'D', 5 => 'E', 6 => 'F', 7 => 'G', 8 => 'H', 9 => 'I', 10 => 'J', 11 => 'K', 12 => 'L', 13 => 'M', 14 => 'N', 15 => 'O', 16 => 'P', 17 => 'Q', 18 => 'R', 19 => 'S', 20 => 'T', 21 => 'U', 22 => 'V', 23 => 'W', 24 => 'X', 25 => 'Y', 26 => 'Z');

                if ($highestRow > 201) {
                    show(0, '每次最多提交两百行数据，请分割文件后再进行提交');
                }
                if ($highestColumn != 'E') {
                    show(0, '文档数据不符合规范', $highestColumn);
                }
                // 一次读取一列
                $res = $defeated = $succeed = array();

                for ($row = 2; $row <= $highestRow; $row++) {
                    for ($column = 0; $arr[$column] != 'E'; $column++) {
                        $val = $sheet->getCellByColumnAndRow($column, $row)->getValue();

                        $res[$row - 2][$column] = $val;
                    }
                    $uid = M('User')->where("gid='%s' and game_user='%s'", $gid, $res[$row - 2][0])->getField('id');

                    if ($uid) {
                        $res[$row - 2]['id'] = $uid;
                        array_push($succeed, $res[$row - 2]);
                    } else {
                        array_push($defeated, $res[$row - 2]);
                    }
                }
//                匹配成功的写入数据库
                $Data = M('Data');
                $Data->startTrans();
                $DataList = array();
                foreach ($succeed as $i => $item) {
                    $DataList[$i]['uid'] = $item['id'];
                    $DataList[$i]['gid'] = $gid;
                    $DataList[$i]['date'] = $date;
                    $DataList[$i]['sell'] = $item[1];
                    $DataList[$i]['sell_count'] = $item[2];
                    $DataList[$i]['recycle'] = $item[3];
                    $DataList[$i]['recycle_count'] = $item[4];
                }

                try {
                    if ($Data->addAll($DataList)) {
//                        匹配失败的
                        $Data->commit();

                        $objPHPExcel = new \PHPExcel();
                        $Sheet = $objPHPExcel->getActiveSheet();

                        $Sheet
                            ->setCellValue('A1', '游戏ID')
                            ->setCellValue('B1', '销售总量')
                            ->setCellValue('C1', '销售笔数')
                            ->setCellValue('D1', '回收总量')
                            ->setCellValue('E1', '回收笔数');
                        $i=1;
                        foreach ($defeated as $item) {
                            $i++;
                                $Sheet
                                    ->setCellValueExplicit('A' . $i, $item[0])
                                    ->setCellValueExplicit('B' . $i, $item[1])
                                    ->setCellValueExplicit('C' . $i, $item[2])
                                    ->setCellValueExplicit('D' . $i, $item[3])
                                    ->setCellValueExplicit('E' . $i, $item[4]);
                        }
                        $Sheet->getColumnDimension('A')->setAutoSize(true);
                        $Sheet->getColumnDimension('B')->setAutoSize(true);
                        $Sheet->getColumnDimension('C')->setAutoSize(true);
                        $Sheet->getColumnDimension('D')->setAutoSize(true);

                        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
                        $objWriter->save($upload->rootPath . $info['file']['savepath'] . 'defeated_' . $info['file']['savename']);

                    } else {
                        $Data->rollback();
                        show(0, '导入失败');
                    }
                } catch (\Think\Exception $e) {
                    $Data->rollback();
                    show(0, $e->getMessage());
                }

//                匹配失败的处理
                show(1, '导入成功！成功导入' . sizeof($succeed) . '条记录。失败' . sizeof($defeated) . '条记录。' . '<a style="color:red" href="' . __ROOT__ . '/' . $upload->rootPath . $info['file']['savepath'] . 'defeated_' . $info['file']['savename'] . '">下载文件</a>');
            }
        }
        $GameData = D('Game')->select();
        $this->assign('GameData', $GameData);

        $this->display('data-import');
    }

}